import { Modal, Spin } from "antd";
import React, { useEffect, useState, useImperativeHandle } from "react";
import { FCForm } from "@components";
import { useDistrictConfig } from "./config";
import { session } from '@core'
import styles from "../styles/module.module.css";

const District = ({districtRef, queryFormRef}) => {
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)

  const onCancel = (isQuery = false) => {
    session.remove('cfgAreaId')
    setOpen(false)
    if (isQuery) {
      queryFormRef.current.submit()
    }
  }

  const { formRef, formProps, initMap, getBoundary, setProvinceListFun, setLabelLoading, setProvinceList, setCityList, setCountyList} = useDistrictConfig( setLoading, onCancel)

  useEffect(() => {
    if (open) {
      setTimeout(() => {
        initMap();
      }, 200);
    }
  }, [open]);

  //暴露给父组件 
  useImperativeHandle(districtRef, () => ({
    setOpen: (data) => setFormValue(data)
  }))

  const setFormValue = (data) => {
    setOpen(true)
    if (!data) return
    session.set('cfgAreaId', data.cfgAreaId)
    const {provinceName, cityName, countyName, provinceCode, cityCode} = data
    setProvinceListFun({ type: "province", code: "" }, setProvinceList, setLabelLoading)
    setTimeout(() => {
      const form = formRef.current.getForm()
      form.setFieldsValue({...data})
      if(provinceCode) {
        const code = form.getFieldValue('provinceCode')
        setProvinceListFun({ type: "city", code  }, setCityList, setLabelLoading)
      }
      if(cityCode) {
        const code = form.getFieldValue('cityCode')
        setProvinceListFun({ type: "county", code  }, setCountyList, setLabelLoading)
      }
      if (!(provinceName || cityName || countyName)) return
      getBoundary(provinceName + cityName + countyName)
    }, 1000);
  }

  return (
    <Modal
      className={styles.district}
      centered
      closable={false}
      open={open}
      footer={null}
      width={1800}
      bodyStyle={{ height: "960px", position: "relative", padding: "0" }}
      destroyOnClose={true}
    >
      <Spin size="large" spinning={loading}>
        <FCForm {...formProps}/>
        <div id='riskAreaContainer'></div>
      </Spin>
    </Modal>
  );
};

export default District;
